<?php
/**
 * Created by litong on Date: 2019/4/10 0010 下午 5:21
 */

namespace office\excel;

use PHPExcel;
use PHPExcel_IOFactory;

include_once '../../lib/PHPExcel/PHPExcel/IOFactory.php';

class PHPExcelStudy {
  /**
   * 读取Excel文件
   */
  public function study1() {
    $filePath = "demo1.xlsx";
    try {
      $fileType = PHPExcel_IOFactory::identify($filePath); //获取文件的类型
      $objReader = PHPExcel_IOFactory::createReader($fileType); //根据文件创建reader
      $objPHPExcel = $objReader->load($filePath); //装载文件
    } catch (Exception $e) {
      $absolutePath = pathinfo($filePath, PATHINFO_BASENAME);
      die("读取PHP文件发生错误" . $absolutePath . $e->getMessage());
    }
    $sheet = $objPHPExcel->getSheet(0);//获取第一个sheet
    $highestRow = $sheet->getHighestRow(); //获取所有行数
    $highestColumn = $sheet->getHighestColumn(); //获取所有列数
    for ($i = 1; $i < $highestRow + 1; $i++) {
      $area = 'A' . $i . ':' . $highestColumn . $i;//==>A1:D1 第一行区域
      $data = $sheet->rangeToArray($area, null, true, false);
      var_dump($data);
      echo "<br/>";
    }
  }

  /**
   * 导出信息到Excel文件
   */
  public function study2() {
    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreated("李通")
      ->setLastModifiedBy("最后的更改者")
      ->setTitle("文档标题")
      ->setSubject("文件主题")
      ->setDescription("文档描述")
      ->setKeywords("设置文档关键词")
      ->setCategory("设置文档分类");

    $objPHPExcel->setActiveSheetIndex(0)
      ->setCellValue("A1", 你好)
      ->setCellValue("B1", "世界");

    $objPHPExcel->getActiveSheet()->setCellValue('A8', "你好世界");
    $objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
    $objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);

    $value = "-ValueA\n-Value B\n-Value C";
    $objPHPExcel->getActiveSheet()->setCellValue('A10', $value);
    $objPHPExcel->getActiveSheet()->getRowDimension(10)->setRowHeight(-1);
    $objPHPExcel->getActiveSheet()->getStyle('A10')->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->getStyle('A10')->setQuotePrefix(true);

    // 重命名工作sheet
    $objPHPExcel->getActiveSheet()->setTitle('第一个sheet');

    // 设置第一个sheet为工作的sheet
    $objPHPExcel->setActiveSheetIndex(0);

    // 保存Excel 2007格式文件，保存路径为当前路径，名字为export.xlsx
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save('export.xlsx');


    // 保存Excel 95格式文件，，保存路径为当前路径，
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('export.xls');
  }
}

$study = new PHPExcelStudy();
//$study->study1();
$study->study2();